package com.auto.learning.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.Handle;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.SharedPreferencesUtils;

public class SetPasswordActivity extends Activity implements OnClickListener {
	
	private final static int SET_PASSWORD_SUCCESS = 1;
	private final static int SET_PASSWORD_FAIL = 2;
	private final static int USER_BIND_TEL_SUCCESS = 3;
	
	private LinearLayout activity_base_back;
	String veryPhone,telCode;
	TextView tv_submit;
	EditText et_ps1,et_ps2;
	ImageView image_backgroup;
	
	private int type = 1; //1为新用户注册，2为手机验证,3用户bing新手机号码
	
	private Handle handle = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SET_PASSWORD_SUCCESS:
				if (type == 1) {
					CommonMethod.makeNotice(SetPasswordActivity.this, "注册成功");
				} else if (type == 2 ){
					CommonMethod.makeNotice(SetPasswordActivity.this, "密码修改成功");
				}
				finish();
				break;
			case SET_PASSWORD_FAIL:
				CommonMethod.makeNotice(SetPasswordActivity.this, msg.obj.toString());
				break;
			case 3:
				ResponeResult telResult = (ResponeResult) msg.obj;
				if (telResult != null) {
					try {
						JSONObject json = new JSONObject(telResult.getData());
						int userId = json.getInt("userId");
						int needFresh = json.getInt("needFresh");
						SharedPreferencesUtils.setParam(SetPasswordActivity.this, HttpRequestHelper.USERID, userId);
						MyUserInfo.getInstance().getUserInfoBean().setIsBindTel(2);
						setResult(110);
						finish();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				CommonMethod.makeNotice(SetPasswordActivity.this, msg.obj+"");
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set_password_activity);
		initView();
	}

	private void initView() {
		Intent intent = getIntent();
		veryPhone = intent.getStringExtra("tel");
		telCode = intent.getStringExtra("telCode");
		type = intent.getIntExtra("type", 1);
		image_backgroup = (ImageView) findViewById(R.id.image_backgroup);
		image_backgroup.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.login_bg));
		activity_base_back = (LinearLayout) findViewById(R.id.activity_base_back);
		tv_submit = (TextView) findViewById(R.id.tv_submit);
		et_ps1 = (EditText) findViewById(R.id.et_ps1);
		et_ps2 = (EditText) findViewById(R.id.et_ps2);
		activity_base_back.setOnClickListener(this);
		tv_submit.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.activity_base_back:
				finish();
				break;
			case R.id.tv_submit:
				submit();
				break;
		}
	}
	
	private void submit(){
		Pattern password = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$");// 密码正则表达式数字和字母
		String et1 = et_ps1.getText().toString();
		String et2 = et_ps2.getText().toString();
		if (TextUtils.isEmpty(et1)) {
			CommonMethod.makeNotice(this, "密码不能为空");
			return;
		}
		if (TextUtils.isEmpty(et2)) {
			CommonMethod.makeNotice(this, "密码不能为空");
			return;
		}
		/*if (!password.matcher(et1).matches()) {
			CommonMethod.makeNotice(this, "密码格式错误");
			return;
		}*/
		if (!et1.equals(et2)) {
			CommonMethod.makeNotice(this, "两次密码不一致");
			return;
		}
		if (type == 1) {
			register(et1);
		}else if (type == 2){
			setPassword(et1);
		}else if (type == 3) {
			HttpRequestHelper.BindTel(SetPasswordActivity.this, veryPhone, et1, handle, USER_BIND_TEL_SUCCESS);
		}
	}
	
	public void register(final String newPwd){

		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				String err = "";
				int isOK = 1;
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("tel", veryPhone));
					params.add(new BasicNameValuePair("telCode", telCode));
					params.add(new BasicNameValuePair("userPwd",newPwd));
					params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(SetPasswordActivity.this, HttpRequestHelper.USERID, 0))));
					HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.REGISTER, params, SetPasswordActivity.this);
					String result = HttpHelper.entity2String(entity);
					JSONObject jObject = new JSONObject(parseResultJson(result));
					int resultCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
					if (resultCode == 0) {
						isOK = 0;
					} else {
						isOK = 1;
						err = jObject.getString(HttpCommonInfo.RESULT_MSG);
					}
				} catch (ClientProtocolException e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} catch (IOException e) {
					err = getResources().getString(R.string.connect_err_io);
					isOK = 1;
				} catch (Exception e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} finally {
					switch (isOK) {
					case 0:
						handle.sendEmptyMessage(SET_PASSWORD_SUCCESS);
						break;
					case 1:
						handle.obtainMessage(SET_PASSWORD_FAIL, err).sendToTarget();
						break;
					}
				}
			}
		});
	}
	
	
	public void setPassword(final String newPwd){

		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				String err = "";
				int isOK = 1;
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("tel", veryPhone));
					params.add(new BasicNameValuePair("telCode", telCode));
					params.add(new BasicNameValuePair("newPwd",newPwd));
					HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.FORGET_PWD, params, SetPasswordActivity.this);
					String result = HttpHelper.entity2String(entity);
					JSONObject jObject = new JSONObject(parseResultJson(result));
					int resultCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
					if (resultCode == 0) {
						isOK = 0;
					} else {
						isOK = 1;
						err = jObject.getString(HttpCommonInfo.RESULT_MSG);
					}
				} catch (ClientProtocolException e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} catch (IOException e) {
					err = getResources().getString(R.string.connect_err_io);
					isOK = 1;
				} catch (Exception e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} finally {
					switch (isOK) {
					case 0:
						handle.sendEmptyMessage(SET_PASSWORD_SUCCESS);
						break;
					case 1:
						handle.obtainMessage(SET_PASSWORD_FAIL, err).sendToTarget();
						break;
					}
				}
			}
		});
	}
	
	public String parseResultJson(String result) throws JSONException {
		JSONObject jObject = new JSONObject(result);
		result = jObject.getString(HttpCommonInfo.RESULT);
		return result;
	}
}
